/*
 * @Author: your name
 * @Date: 2020-12-30 17:28:53
 * @LastEditTime: 2021-01-12 15:13:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \node-server\utils\jwt.js
 */
const jwt = require('jsonwebtoken')
const expressJwt = require('express-jwt');
const Result = require('../models/result.js');
const { PRIVATE_KEY, JWT_EXPIRED } = require('./constant')
// 生成token
const createToken = (username) => {
  const token = jwt.sign(
    { username },
    PRIVATE_KEY,
    { expiresIn: JWT_EXPIRED }
  )
  return token
}
//解析token
function parseToekn(req) {
  const authorization = req.get('Authorization')
  const token = authorization.indexOf('Bearer') >= 0 ? authorization.replace('Bearer ', '') : authorization
  return jwt.verify(token, PRIVATE_KEY)
}

// admin校验token
const adminJwtAuth = expressJwt({
  secret: PRIVATE_KEY,
  algorithms: ['HS256'],
  credentialsRequired: true, // 设置为false就不进行校验了，游客也可以访问
}).unless({
  path: [
    '/admin',
    '/admin/users/login',
    '/admin/users/register',
    /^\/admin\/static/,
    // '/admin/img',
    // /^\/public/,
  ], // 设置 jwt 认证白名单
});
// web校验token
/* const webJwtAuth = expressJwt({
  secret: PRIVATE_KEY,
  algorithms:['HS256'],
  credentialsRequired: true, // 设置为false就不进行校验了，游客也可以访问
}).unless({
  path: [ 
    '/admin',
    '/admin/users/login',
    '/admin/users/register',
    '/admin/img',
    /^\/public/,
  ], // 设置 jwt 认证白名单
}); */


//token失效异常抛出
const tokenLoseCatch = (err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    new Result(null, 'token失效', {
      error: err.status,
      errorMsg: err.name
    }).expired(res.status(err.status))
  } else {
    const msg = (err && err.message) || '系统错误'
    const statusCode = (err.output && err.output.statusCode) || 500;
    const errorMsg = (err.output && err.output.payload && err.output.payload.error) || err.message
    new Result(null, msg, {
      error: statusCode,
      errorMsg
    }).fail(res.status(statusCode))
  }
}

module.exports = { createToken, parseToekn , adminJwtAuth, tokenLoseCatch }
